package com.ethannhu.todaynews.util

import android.text.TextUtils
import android.widget.ImageView
import com.alibaba.sdk.android.oss.OSSClient
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.ethannhu.todaynews.AppContext
import com.ethannhu.todaynews.R
import com.ethannhu.todaynews.config.Config

/**
 * 图片工具类
 */
object ImageUtil {

    /**
     * 显示本地图片
     *
     * @param view
     * @param data
     */
    fun showLocalImage(view: ImageView, data: String) {
        //获取通用配置
        val options: RequestOptions = getCommonRequestOptions()

        //使用Glide显示图片
        Glide.with(view.context)
            .load(data)
            .apply(options)
            .into(view!!)
    }

    /**
     * 显示网络图片
     */
    fun show(view: ImageView, data: String?, defaultRes: Int = R.drawable.placeholder) {
        if (TextUtils.isEmpty(data)) {
            view.setImageResource(defaultRes)
        } else {
            //已经是网络图片或者是本地路径
            val url: String = if (data!!.startsWith("http") || data.startsWith("/")) {
                data
            } else {
                // OSS私有了，用这个访问，但是还是不行
                val originUrl = ResourceUtil.resourceUri(data)
                val credentialProvider = OSSPlainTextAKSKCredentialProvider(Config.ALIYUN_AK, Config.ALIYUN_SK)
                val oss = OSSClient(AppContext.instance, Config.BUCKET_ENDPOINT, credentialProvider)
                oss.presignConstrainedObjectURL(Config.ALIYUN_OSS_BUCKET_NAME, originUrl, 3600) // 有效期1小时
            }
            //获取通用配置
            val options: RequestOptions = getCommonRequestOptions()

            Glide.with(view)
                .load(url)
                .apply(options)
                .into(view)
        }
    }

    /**
     * 获取公共配置
     *
     * @return
     */
    private fun getCommonRequestOptions(): RequestOptions {
        //占位图
        //options.placeholder(R.drawable.placeholder);

        //从中心裁剪
        //options.centerCrop();

        return RequestOptions()
            .error(R.drawable.food) //出错后显示的图片  //包括：图片不存在等情况
            .diskCacheStrategy(DiskCacheStrategy.NONE) //开启磁盘缓存
    }

    fun showAvatar(iconView: ImageView, icon: String?) {
        show(iconView, icon, R.drawable.default_avatar)
    }
}
